package com.code2roc.jarmanage.servlet.redis;

import com.code2roc.jarmanage.model.Result;
import com.code2roc.jarmanage.util.CommonUtil;
import com.code2roc.jarmanage.util.ConvertUtil;
import com.code2roc.jarmanage.util.JedisUtil;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class AddKeyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = Result.okResult();
        HashMap params = CommonUtil.getParamMap(req);
        int dbIndex = ConvertUtil.convert2Int(params.get("dbIndex"));
        String key = ConvertUtil.convert2String(params.get("key"));
        String keyType = ConvertUtil.convert2String(params.get("keyType"));
        long keyExpire = ConvertUtil.convert2Int(params.get("keyExpire"));
        String value = ConvertUtil.convert2String(params.get("value"));
        Jedis client = JedisUtil.getClient();
        if (keyType.equals("string")) {
            JedisUtil.setString(key, value, client, dbIndex);
        } else if (keyType.equals("list")) {
            JedisUtil.setList(key, value, client, dbIndex);
        } else if (keyType.equals("set")) {
            JedisUtil.setSet(key, value, client, dbIndex);
        } else if (keyType.equals("zset")) {
            double score = ConvertUtil.convert2Double(params.get("score"));
            JedisUtil.setZset(key, value, score, client, dbIndex);
        } else if (keyType.equals("hash")) {
            String hashKey = ConvertUtil.convert2String(params.get("hashKey"));
            JedisUtil.setHash(key, hashKey, value, client, dbIndex);
        }
        if (keyExpire != -1) {
            JedisUtil.setExpire(key, client, keyExpire, dbIndex);
        }else{
            JedisUtil.setPersist(key, client, dbIndex);
        }
        resp.getWriter().println(result.toString());
    }
}
